//
//  SNLocationManager.m
//  wrongTopic
//
//  Created by wangsen on 16/1/16.
//  Copyright © 2016年 wangsen. All rights reserved.
//

#import "SNLocationManager.h"

static SNLocationManager * _manager = nil;

@interface SNLocationManager () <CLLocationManagerDelegate>
{
    UpdateLocationSuccessBlock _successBlock;
    UpdateLocationErrorBlock _errorBlock;
}

@property (nonatomic, strong) CLLocationManager * locationManager;//定位管理器
@end


@implementation SNLocationManager

+ (instancetype)shareLocationManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _isAlwaysUse = NO;
        _isRealTime = NO;
        _desiredAccuracy = kCLLocationAccuracyKilometer;
    }
    return self;
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
    }
    return _locationManager;
}

- (void)startUpdatingLocationWithSuccess:(UpdateLocationSuccessBlock)success andFailure:(UpdateLocationErrorBlock)error
{
    
    _successBlock = [success copy];
    _errorBlock = [error copy];
    
    //定位服务是否可用
    BOOL isLocationEnabled = [CLLocationManager locationServicesEnabled];
    if (!isLocationEnabled) {
        NSLog(@"请打开定位服务");
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请打开定位服务，才能使用定位功能" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    self.locationManager.delegate = self;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0) {
        //精度
        self.locationManager.desiredAccuracy = _desiredAccuracy;
        //更新距离
        if (_distanceFilter == 0) {
            self.locationManager.distanceFilter = kCLDistanceFilterNone;
        }else{
            self.locationManager.distanceFilter = _distanceFilter;
        }
        //定位开始
        [self.locationManager startUpdatingLocation];
    }

}

#pragma mark - 状态改变时调用 IOS 8新增方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    //是否具有定位权限
    if (status == kCLAuthorizationStatusNotDetermined ||
        status == kCLAuthorizationStatusRestricted ||
        status == kCLAuthorizationStatusDenied ) {
        
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            if (!_isAlwaysUse) {
                [manager requestWhenInUseAuthorization];
            } else {
                [manager requestAlwaysAuthorization];
            }
        }
        if (_isAlwaysUse) {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
                manager.allowsBackgroundLocationUpdates = YES;
            }
        }
    } else {
        //精度
        manager.desiredAccuracy = _desiredAccuracy;
        //更新距离
        if (_distanceFilter == 0) {
            manager.distanceFilter = kCLDistanceFilterNone;
        }else{
            manager.distanceFilter = _distanceFilter;
        }
        //定位开始
        [manager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation * location = locations.firstObject;
    CLGeocoder * geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark * placemark = placemarks.firstObject;
        _successBlock(location,placemark);
    }];
    
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLGeocodeCompletionHandler handle = ^(NSArray *placemarks,NSError *error){
        for (CLPlacemark * placeMark in placemarks){
            
            NSDictionary *addressDic=placeMark.addressDictionary;
            
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            NSString* lastAddress=[NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,street];
        }
 
    };
    [clGeoCoder reverseGeocodeLocation:location completionHandler:handle];
    
    //关闭定位
    if (!_isRealTime) {
        [manager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
    _errorBlock(region,error);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    [manager stopUpdatingLocation];
    switch([error code]) {
        case kCLErrorDenied:
            //            [self openGPSTips];
            break;
        case kCLErrorLocationUnknown:
            break;
        default:
            break;
    }
}


-(void)geocodeLocation:(CLLocationCoordinate2D)locon andLocaiontBlock:(void(^)(NSDictionary *data, NSError *error))dataBlock
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    CLLocation *location = [[CLLocation alloc]initWithLatitude:locon.latitude longitude:locon.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0 ){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //placemark.locality 城市 四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            NSLog(@"------- %@",placemark.addressDictionary);
            if (placemark.addressDictionary) {
                dataBlock(placemark.addressDictionary,nil);
            }
        }else if (error == nil && [array count] == 0){
            NSLog(@"No results were returned.");
        }else if (error != nil){
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
}

@end
